package com.mad.bikepony.service.persistence;

import java.math.BigInteger;
import java.util.List;

import com.liferay.portal.kernel.dao.orm.SQLQuery;
import com.liferay.portal.service.persistence.impl.BasePersistenceImpl;
import com.mad.bikepony.model.Agent;

public class AgentFinderImpl extends BasePersistenceImpl<Agent> implements AgentFinder {

	
	@SuppressWarnings("unchecked")
	public Long findLeastLoadedAgent()
	{
		String query="select Delivery.agentId from bp_delivery as Delivery group by agentId order by count(Delivery.deliveryId) ASC limit 1";
		SQLQuery sqlQuery = openSession().createSQLQuery(query);
		
		List<BigInteger> result = (List<BigInteger>)sqlQuery.list();
		if(result.isEmpty())
			return null;
		else 
			return result.get(0).longValue();
	}
}
